<?php

namespace app\mobile\controller\rating_scale\report;

use app\BaseController;
use app\model\ConfigModel;
use app\model\InterpretationRecordModel;
use app\model\not_del\UserModel as NotDelUserModel;
use app\model\questionnaire\QuestionnaireTaskModel;
use app\model\questionnaire\QuestionnaireTaskUserModel;
use app\model\questionnaire\QuestionnaireTaskUserResultModel;
use app\model\RatingScaleModel;
use app\model\RatingScaleQuestionModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskModel;
use app\model\TaskUserModel;
use app\model\TaskUserResultModel;
use app\model\UserModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 自我测评报告列表
     * @return bool|string
     */
    public function selfList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $ratingScaleWhere = [];
            if (!empty($param['name'])) {
                $ratingScaleWhere[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['type_id'])) {
                $ratingScaleWhere[] = ['type_id', '=', $param['type_id']];
            }
            if (!empty($ratingScaleWhere)){
                $ratingScaleWhere[] = ['unit_id', '=', $this->userData['unit_id']];
                $RatingScaleModel = new RatingScaleModel();
                $rating_scale_id = $RatingScaleModel->where($ratingScaleWhere)->column('id');
                if (count($rating_scale_id) > 0) {
                    $where[] = ['rating_scale_id', 'in', $rating_scale_id];
                }else{
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['is_explain'])) {
                $where[] = ['is_explain', '=', $param['is_explain']];
            }
            if (!empty($param['answer_role'])) {
                $where[] = ['answer_role', '=', $param['answer_role']];
            }
            $where[] = ['uid', '=', $this->userData['id']];
            $where[] = ['user_del','=',0];
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $query = $SelfEvaluationResultModel->where($where);
            $data = $query->with([
                'ratingScale'
            ])->order('id','desc')->select()->toArray();
            $data2 = [];
            foreach ($data as $value) {
                $date = date('Y年m月份',$value['time']);
                $data2[$date][] = $value;
            }
            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告列表
     * @return bool|string
     */
    public function taskList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $ResultWhere = [];
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $ResultWhere[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $ResultWhere[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $ResultWhere[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['answer_role'])) {
                $ResultWhere[] = ['answer_role', '=', $param['answer_role']];
            }
            if (!empty($param['type_id'])) {
                $RatingScaleModel = new RatingScaleModel();
                $rating_scale_id = $RatingScaleModel->where([
                    ['type_id', '=', $param['type_id']],
                    ['unit_id', '=', $this->userData['unit_id']],
                ])->column('id');
                $ResultWhere[] = ['rating_scale_id', 'in', $rating_scale_id];
            }
            $ResultWhere[] = ['uid', '=', $this->userData['id']];
            $ResultWhere[] = ['user_del', '=', 0];
            $TaskUserResultModel = new TaskUserResultModel();
            $taskList = $TaskUserResultModel->where($ResultWhere)->field('task_id,answer_role,time')->select()->toArray();
            $taskData = [];
            foreach ($taskList as $v) {
                $taskData[$v['task_id']][] = $v;
            }
            $task_ids = array_column($taskList, 'task_id');
            $TaskUserModel = new TaskUserModel();
            $finishIds = $TaskUserModel->where([
                ['task_id', 'in', $task_ids],
                ['uid', '=', $this->userData['id']],
                ['is_finish', '=', 0]
            ])->column('task_id');
            $finishIds = array_unique($finishIds);
            if (isset($param['is_finish']) && strlen($param['is_finish']) > 0) {
                if ($param['is_finish'] == 1) {
                    $task_ids = array_diff($task_ids, $finishIds);
                    if (count($task_ids) > 0) {
                        $where[] = ['id', 'in', $task_ids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                } else {
                    if (count($finishIds) > 0) {
                        $where[] = ['id', 'in', $finishIds];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
            } else {
                $where[] = ['id', 'in', $task_ids];
            }
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', 'like', '%' . $param['uid'] . '%'];
            }
            $NotDelUserModel = new NotDelUserModel();
            if (isset($param['role_mode'])) {
                $uid = $NotDelUserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['role_mode', '=', $param['role_mode']],
                ])->column('id');
                if (count($uid)){
                    $where[] = ['uid', 'in', $uid];
                }else{
                    $where[] = ['id', '=', -1];
                }
            }
            $TaskModel = new TaskModel();
            $query = $TaskModel->where($where);
            $data = $query->with([
                'userName'
            ])->order('id','desc')->select()->toArray();
            $data2 = [];
            foreach ($data as $item) {
                $item['time'] = $taskData[$item['id']][0]['time']??0;
                $item['answer_role'] = $taskData[$item['id']][0]['answer_role']??1;
                $item['finish_num'] = count($taskData[$item['id']]??[]);
                $date = date('Y年m月份',$item['time']);
                $data2[$date][] = $item;
            }
            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告详情
     * @return bool|string
     */
    public function taskInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TaskModel = new TaskModel();
            $taskInfo = $TaskModel->with(['userName'])->find($param['id']);
            if (!$taskInfo) throw new \Exception('参数错误！');
            $UserModel = new UserModel();
            $userInfo = $UserModel->find($this->userData['id']);
            $TaskUserModel = new TaskUserModel();
            $TaskUserList = $TaskUserModel->where([
                ['task_id', '=', $param['id']],
                ['uid', '=', $this->userData['id']],
            ])->with([
                'ratingScale'
            ])->select();
            return success([
                'taskInfo' => $taskInfo,
                'userInfo' => $userInfo,
                'taskUserList' => $TaskUserList
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务报告答题情况
     * @return bool|string
     */
    public function taskAnsweringSituation(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TaskUserResultModel = new TaskUserResultModel();
            $info = $TaskUserResultModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            //获取量表题目
            $AnswerIds = json_decode($info['question_answer'], true);
            $RatingScaleQuestionModel = new RatingScaleQuestionModel();
            $QuestionList = $RatingScaleQuestionModel->field('id,num,name,type')
                ->where('rating_scale_id', '=', $info['rating_scale_id'])
                ->with([
                    'RatingScaleQuestionAnswer' => function ($query) {
                        $query->field('id,question_id,name,score');
                    }
                ])->select()->toArray();
            foreach ($QuestionList as &$QuestionAnswer) {
                foreach ($QuestionAnswer['RatingScaleQuestionAnswer'] as &$item) {
                    if (in_array($item['id'], $AnswerIds)) {
                        $item['select'] = 1;
                    } else {
                        $item['select'] = 0;
                    }
                }
            }
            return success($QuestionList);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取今日申请解读次数
     * @return bool|string
     */
    public function getExplainNum(): bool|string
    {
        try {
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['key','=','evaluation_report']
            ])->value('value');
            $config = json_decode($config,true);
            $InterpretationRecordModel = new InterpretationRecordModel();
            //解读次数
            $explain_num = $InterpretationRecordModel->where([
                ['uid','=',$this->userData['id']],
                ['time','>',strtotime(date('Y-m-d'))]
            ])->count();
            if ($config['is_explain']??0 == 1){
                $explain = $config['explain_num'] - $explain_num;
            }else{
                $explain = '不限';
            }
            $UserModel = new UserModel();
            $name = $UserModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['role_mode','=',2]
            ])->orderRand()->value('name');
            return success([
                'explain_num' => $explain,
                'user_name' => $name
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 测评首页
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $TaskModel = new TaskModel();
            $TaskUserModel = new TaskUserModel();
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $taskResult = $TaskUserResultModel->where('uid','=',$this->userData['id'])->count();
            $selfResult = $SelfEvaluationResultModel->where('uid','=',$this->userData['id'])->count();
            $questionnaire_result = $QuestionnaireTaskUserResultModel->where('uid','=',$this->userData['id'])->count();


            //未完成任务
            $task_id = $TaskUserModel->where([
                ['uid','=',$this->userData['id']],
                ['is_finish','=',0]
            ])->distinct(true)->column('task_id');
            if (!empty($task_id)){
                $taskCount = $TaskModel->where([
                    ['id','in',$task_id],
                    ['status','=',2]
                ])->count();
            }else{
                $taskCount = 0;
            }

            //自我
            $RatingScaleModel = new RatingScaleModel();
            $self_count = $RatingScaleModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['is_self_evaluation','=',1],
                ['status','=',1]
            ])->count();

            //问卷
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $task_id = $QuestionnaireTaskUserModel->where([
                ['uid','=',$this->userData['id']],
                ['is_finish','=',0]
            ])->distinct(true)->column('task_id');
            if (!empty($task_id)){
                $QuestionnaireTaskModel = new QuestionnaireTaskModel();
                $questionnaireCount = $QuestionnaireTaskModel->where([
                    ['id','in',$task_id],
                    ['status','=',2]
                ])->count();
            }else{
                $questionnaireCount = 0;
            }

            return success([
                'self_count' => $self_count,
                'task_count' => $taskCount,
                'questionnaire_count' => $questionnaireCount,
                'self_result' => $selfResult,
                'task_result' => $taskResult,
                'questionnaire_result' => $questionnaire_result,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}